package com.wzdigit.wms.ws.config;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class FileExtension {

	/**
	 * 文件上传
	 * 
	 * @param filePath, request, path , fileName
	 * @return fileUrl(相对路径)
	 * @throws Exception
	 */
	public static String SaveVirtualPath(MultipartFile uploadFile, String filePath, String fileName, String modular,
			String location) throws Exception {
		String fileNameString = uploadFile.getOriginalFilename();
		if (!fileName.isEmpty() && fileName != "" && fileName != null) {
			fileNameString = fileName;
		}
		try {
			String relativePath = (filePath == "" || filePath == null) ? modular + "/" : filePath;
			String absolutePath = location + relativePath;
			File targetFile = new File(absolutePath, fileNameString);
			if (!targetFile.getParentFile().exists()) {
				targetFile.getParentFile().mkdirs();
			}
			InputStream inputStream = uploadFile.getInputStream();
			FileOutputStream fileOutputStream = new FileOutputStream(absolutePath + fileNameString);
			byte buffer[] = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(buffer)) > 0) {
				fileOutputStream.write(buffer, 0, len);
			}
			inputStream.close();
			fileOutputStream.close();
			return relativePath + fileNameString;
		} catch (Exception ex) {
			throw ex;
		}
	}

	public static String upLoadFile(MultipartFile uploadFile, String filePath, String fileName, String modular,
			String location) throws Exception {
		String fileNameString = uploadFile.getOriginalFilename();
		if (!fileName.isEmpty() && fileName != "" && fileName != null) {
			fileNameString = fileName;
		}
		try {
			String resultPath = (filePath == "" || filePath == null) ? location + modular + "/" : filePath;
			File targetFile = new File(resultPath, fileNameString);
			if (!targetFile.getParentFile().exists()) {
				targetFile.getParentFile().mkdirs();
			}
			InputStream inputStream = uploadFile.getInputStream();
			FileOutputStream fileOutputStream = new FileOutputStream(resultPath + fileNameString);
			byte buffer[] = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(buffer)) > 0) {
				fileOutputStream.write(buffer, 0, len);
			}
			inputStream.close();
			fileOutputStream.close();
			return resultPath + fileNameString;
		} catch (Exception ex) {
			throw ex;
		}
	}
}
